import { useMemo } from 'react'
import dayjs from 'dayjs'
import { Badge, Button, Popover, Space, Tabs, Tag, Tooltip, Typography } from 'antd'
import { BaseType } from 'antd/es/typography/Base'
import { EditOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons'
import { StatusPanelDef } from '@ag-grid-community/core'

import { CusAgGrid, ICusAgGridProps } from '@/components/CusAgGrid'
import { UnifiedPagination } from '@/components/UnifiedPagination'
import { addAGCellTexty } from '@oBiz/components/addTexty'
import { getStatusGroupName, getStatusName } from '@oBiz/components/EventSelect/utils'
import { AddOrEditEventTemplateDrawer } from './AddOrEditEventTemplateDrawer'
import { Filter } from './Filter'
import { IEventTemplateItem, TCellParams, TCol } from './interface'
import { useBoundStore } from './store'
import { useEventTemplateList } from './useEventTemplateList'
import {
  getEnableFlagName,
  getFirstLineName,
  getLocationTypeName,
  getMessageTypeName,
  getShipTrackStatusName,
  getTabIdName,
  getTailLineName,
  getVisibleFlagName,
  popupSlot,
} from './utils'
import styles from './styles.module.less'

const ActionCell = ({ value }: TCellParams<'eventTemplateId'>) => {
  const setReqData = useBoundStore(v => v.setReqData)
  const getData = useBoundStore(v => v.getData)

  if (value == null) return
  return (
    <>
      <Tooltip title="编辑">
        <Button
          type="link"
          icon={<EditOutlined />}
          onClick={() =>
            AddOrEditEventTemplateDrawer.open({
              eventTemplateId: value,
              onSuccess: () => {
                setReqData({ page: 1 })
                getData(true)
              },
            })
          }
        />
      </Tooltip>
    </>
  )
}

const Cell = (p: TCellParams) => {
  const { field } = p.colDef || {}
  switch (field) {
    case 'eventTemplateId': {
      return <ActionCell {...(p as TCellParams<'eventTemplateId'>)} />
    }
    case 'shipTrackRequire': {
      const status = getShipTrackStatusName(p.value as number)
      return <Tag color={p.value === 1 ? 'success' : 'error'}>{status}</Tag>
    }
    case 'messageType': {
      const status = getMessageTypeName(p.value as number)
      const typeList = {
        1: 'success',
        2: 'warning',
        3: 'danger',
      }
      return <Typography.Text type={typeList[p.value as keyof typeof typeList] as BaseType}>{status}</Typography.Text>
    }
    case 'statusGroup': {
      const statusGroup = getStatusGroupName(p.value as number)
      return <Typography.Text>{statusGroup}</Typography.Text>
    }
    case 'status': {
      const status = getStatusName(p.value as number)
      return <Typography.Text>{status}</Typography.Text>
    }
    case 'firstLines': {
      const dom = (p.value as number[])?.map((item, index) => (
        <Tag key={item} color={getFirstLineName.colorOf(item)}>
          {getFirstLineName(item)}
        </Tag>
      ))
      return (
        <Popover content={dom}>
          <Space>
            {(p.value as number[])?.map((item, index) => (
              <Tag key={item} color={getFirstLineName.colorOf(item)}>
                {getFirstLineName(item)}
              </Tag>
            ))}
          </Space>
        </Popover>
      )
    }
    case 'tailLines': {
      const dom = (p.value as number[])?.map((item, index) => (
        <Tag key={item} color={getTailLineName.colorOf(item)}>
          {getTailLineName(item)}
        </Tag>
      ))
      return (
        <Popover content={dom}>
          <Space>{dom}</Space>
        </Popover>
      )
    }
    case 'locationType': {
      const locationType = getLocationTypeName(p.value as number)
      return <Typography.Text>{locationType}</Typography.Text>
    }
    case 'visibleFlag': {
      const visibleFlag = getVisibleFlagName(p.value as number)
      return <Tag color={p.value === 1 ? 'success' : 'error'}>{visibleFlag}</Tag>
    }
    case 'enableFlag': {
      const enableFlag = getEnableFlagName(p.value as number)
      return <Tag color={p.value === 1 ? 'success' : 'error'}>{enableFlag}</Tag>
    }
    default: {
      return addAGCellTexty(p)
    }
  }
}

export const EventTemplate = () => {
  useEventTemplateList()

  const loading = useBoundStore(v => v.request?.loading)
  const data = useBoundStore(v => v.request?.data)
  const page = useBoundStore(v => v.reqData.page)
  const size = useBoundStore(v => v.reqData.size)
  const tabId = useBoundStore(v => v.reqData.tabId)
  const gridRef = useBoundStore(v => v.gridRef)
  const setReqData = useBoundStore(v => v.setReqData)
  const getData = useBoundStore(v => v.getData)
  const tabCount = useBoundStore(v => v.tabCount)
  const getTabCount = useBoundStore(v => v.getTabCount)

  // 勾选统计 & 分页器
  const statusBar = useMemo<ICusAgGridProps['statusBar']>(() => {
    const statusPanels: StatusPanelDef[] = []
    statusPanels.push({
      statusPanel: UnifiedPagination,
      statusPanelParams: UnifiedPagination.defineProps({
        current: page,
        pageSize: size,
        total: data?.total,
        onChange: (page, size) => {
          setReqData({ page, size })
          getData(true)
        },
      }),
    })
    return { statusPanels }
  }, [data?.total, getData, page, setReqData, size])

  // 列配置
  const defaultColDef = useMemo<Partial<TCol>>(
    () => ({
      flex: 1,
      minWidth: 130,
      sortable: false,
      cellRenderer: Cell,
    }),
    [],
  )

  const columnDefs = useMemo(
    () => [
      {
        field: 'templateCn',
        headerName: '中文描述',
        width: 130,
      } satisfies TCol<'templateCn'>,
      {
        field: 'templateEn',
        headerName: '英文描述',
        width: 130,
      } satisfies TCol<'templateEn'>,
      {
        field: 'statusCode',
        headerName: 'Status Code',
        minWidth: 180,
      } satisfies TCol<'statusCode'>,
      {
        field: 'reasonCode',
        headerName: 'Reason Code',
        minWidth: 180,
      } satisfies TCol<'reasonCode'>,
      {
        field: 'shipTrackRequire',
        headerName: 'ShipTrack要求',
        minWidth: 180,
        valueFormatter: ({ value: v }) => getShipTrackStatusName(v),
      } satisfies TCol<'shipTrackRequire'>,
      {
        field: 'messageType',
        headerName: '类型',
        minWidth: 130,
        valueFormatter: ({ value: v }) => getMessageTypeName(v) || '',
      } satisfies TCol<'messageType'>,
      {
        field: 'statusGroup',
        headerName: '对应状态组',
        minWidth: 130,
        valueFormatter: ({ value: v }) => getStatusGroupName(v),
      } satisfies TCol<'statusGroup'>,
      {
        field: 'status',
        headerName: '对应状态',
        minWidth: 130,
        valueFormatter: ({ value: v }) => getStatusName(v),
      } satisfies TCol<'status'>,
      {
        field: 'firstLines',
        headerName: '适用头程运输',
        minWidth: 180,
        valueFormatter: ({ value: v }) => (v ? v.map(getFirstLineName).join('、') : ''),
      } satisfies TCol<'firstLines'>,
      {
        field: 'tailLines',
        headerName: '适用尾程运输',
        minWidth: 180,
        valueFormatter: ({ value: v }) => (v ? v.map(getTailLineName).join('、') : ''),
      } satisfies TCol<'tailLines'>,
      {
        field: 'locationType',
        headerName: 'Location类型',
        minWidth: 180,
        valueFormatter: ({ value: v }) => getLocationTypeName(v) || '',
      } satisfies TCol<'locationType'>,
      {
        field: 'visibleFlag',
        headerName: '客户可见',
        minWidth: 130,
        valueFormatter: ({ value: v }) => getVisibleFlagName(v) || '',
      } satisfies TCol<'visibleFlag'>,
      {
        field: 'enableFlag',
        headerName: '启用',
        minWidth: 130,
        valueFormatter: ({ value: v }) => getEnableFlagName(v) || '',
      } satisfies TCol<'enableFlag'>,
      {
        field: 'updateAt',
        headerName: '更新时间',
        minWidth: 180,
        valueFormatter: ({ value: v }) => (v ? dayjs(v).format($F_YMDHms) : ''),
      } satisfies TCol<'updateAt'>,
      {
        field: 'eventTemplateId',
        headerName: '操作',
        maxWidth: 100,
        pinned: 'right',
      } satisfies TCol<'eventTemplateId'>,
    ],
    [],
  )

  const tabItems = useMemo<{ label: string; key: string }[]>(
    () =>
      getTabIdName.valueList
        .map(v => ({ label: getTabIdName(v), key: String(v) }))
        .map(({ label, key }) => ({
          label: (
            <Space>
              {label}
              <Badge
                count={tabCount.find(v => v.tabId?.toString() === key)?.count ?? 0}
                className={String(tabId) === key ? styles.activeTabCount : styles.tabCount}
              />
            </Space>
          ) as unknown as string,
          key: key.toString(),
        })),
    [tabId, tabCount],
  )

  return (
    <div className={styles.box}>
      <div className={styles.filter}>
        <Filter />
      </div>

      <div className={styles.main}>
        <div className={styles.main_header}>
          <div className={styles.main_header_left}>
            <Tabs
              destroyInactiveTabPane
              onChange={v => {
                gridRef.current?.api?.ensureIndexVisible(0, 'top')
                setReqData({ tabId: Number(v) })
                getData(true)
              }}
              activeKey={String(tabId)}
              items={tabItems}
              tabBarExtraContent={
                <Space>
                  <Button
                    type="default"
                    icon={<ReloadOutlined />}
                    onClick={() => {
                      setReqData({ page: 1 })
                      getData(true)
                    }}
                  >
                    刷新
                  </Button>
                  <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={() =>
                      AddOrEditEventTemplateDrawer.open({
                        eventTemplateId: undefined,
                        onSuccess: () => {
                          setReqData({ page: 1 })
                          getData(true)
                        },
                      })
                    }
                  >
                    新建轨迹模版
                  </Button>
                </Space>
              }
            />
          </div>
        </div>
        <div className={styles.main_body}>
          <CusAgGrid<IEventTemplateItem>
            ref={gridRef}
            loading={loading}
            rowData={data?.records}
            columnDefs={columnDefs}
            defaultColDef={defaultColDef}
            statusBar={statusBar}
          />
        </div>
      </div>
      <popupSlot.Slot />
    </div>
  )
}
